package com.qyer.lxp.service.mail.impl;


import java.io.File;
import java.util.*;


import com.qyer.lxp.common.date.DateUtil;
import com.qyer.lxp.common.file.StringUtil;
import com.qyer.lxp.common.framework.contants.QyerContants;
import com.qyer.lxp.common.framework.util.QyerConfig;
import com.qyer.lxp.common.framework.util.QyerUtils;
import com.qyer.lxp.model.mail.EmailModel;
import com.qyer.lxp.model.price.normal.Price;
import com.qyer.lxp.model.product.normal.PickDropModel;
import com.qyer.lxp.service.mail.ISendEmailService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;


/**
 * 
 * Title. <br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2015年7月15日 下午1:56:41
 * <p>
 * Company: 穷游网
 * <p>
 * Author: zhen.wang@qyer.com
 * <p>
 * Version: 1.0
 * <p>
 */
@Service
public class SendEmailService implements ISendEmailService {

	/**
	 * 测试代码，发布时删除
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EmailModel sendInfo = new EmailModel();

		sendInfo.setTo("zhen.wang@qyer.com;");
		sendInfo.setTitle("spring email 测试");
		sendInfo.setContent("测测");
		ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "applicationContext-mail.xml" });
		SendEmailService emailBO = (SendEmailService) ctx.getBean("sendEmail");
		try {
			emailBO.sendEmailNoAttachFile(sendInfo);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * email发送类
	 */
	private JavaMailSenderImpl javaMail;

	/**
	 * 日志信息类
	 */
	private final Log logger = LogFactory.getLog(SendEmailService.class);

	/**
	 * 邮件信息设置类
	 */
	private MimeMessageHelper messageHelper;

	/**
	 * 
	 */
	public SendEmailService() {
		// TODO Auto-generated constructor stub
	}

	public JavaMailSenderImpl getJavaMail() {
		return javaMail;
	}

	public Log getLogger() {
		return logger;
	}

	public MimeMessageHelper getMessageHelper() {
		return messageHelper;
	}

	@Override
	public int sendEmail(EmailModel emailModel) throws Exception {
		if (null == emailModel.getAttachFileName()) {
			return 2;
		}
		/**
		 * 获得发送人
		 */
		String tmpUserName = emailModel.getFrom();
		/**
		 * 判断邮件用户名是否为空，为空取spring配置文件中的默认用户名
		 */
		if (tmpUserName == null || "".equalsIgnoreCase(tmpUserName)) {
			emailModel.setFrom(javaMail.getUsername());
		}
		/**
		 * 创建一个MimeMessage对象
		 */
		MimeMessage mimeMessage = javaMail.createMimeMessage();
		/**
		 * 创建一个MimeMessageHelper对象
		 */
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GBK");
		// MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
		// true);

		/**
		 * 邮件群发人分析
		 */
		String tmpToUser = emailModel.getTo();
		/**
		 * 群发接收人
		 */
		String[] arrToUser = tmpToUser.split(";");
		/**
		 * 设置发送人
		 */
		messageHelper.setFrom(emailModel.getFrom());
		/**
		 * 设置接收人
		 */

		/**
		 * 设置标题
		 */
		messageHelper.setSubject(emailModel.getTitle());
		/**
		 * 设置内容
		 */
		messageHelper.setText(emailModel.getContent(), true);
		// messageHelper.setText(emailModel.getContent());

		/**
		 * 附件名，类型为数组
		 */
		String[] attachFileName = emailModel.getAttachFileName();
		/**
		 * 附件路径
		 */
		String attachPath = emailModel.getAttachPath();
		/**
		 * 操作系统分隔符
		 */
		String systemSeparator = StringUtil.getSystemParameter("file.separator");
		
		// 要最终发送的附件
		List<String> finalAttachFileName = new ArrayList<String>();
		
		if(attachFileName != null && ArrayUtils.isNotEmpty(attachFileName)){
			for(int i=0; i < attachFileName.length; i ++){
				if(!(null == attachFileName[i])){
					finalAttachFileName.add(attachFileName[i]);
				}
			}
		}
		
		try {
			/** 判断是否有附件，没有附件将不会发送附件 */
			if (finalAttachFileName != null && finalAttachFileName.size() > 0) {
				for (int j = 0; j < finalAttachFileName.size(); j++) {
					messageHelper.addAttachment(MimeUtility.encodeText(finalAttachFileName.get(j)),
							new File(attachPath + systemSeparator+ finalAttachFileName.get(j)));
				}
			} else {
				logger.info("☆☆☆ 没有生成附件，邮件不发送！");
				// 没有数据
				return 3;
			}

			/** 设置发送人 */
			messageHelper.setTo(arrToUser);
			/** 发送邮件 */
			javaMail.send(mimeMessage);
		} catch (Exception ex) {
			logger.error("邮件发送错误！",ex);
			ex.printStackTrace();
		}
		return 1;
	}

	public void setJavaMail(JavaMailSenderImpl javaMail) {
		this.javaMail = javaMail;
	}

	public void setMessageHelper(MimeMessageHelper messageHelper) {
		this.messageHelper = messageHelper;
	}

	@Override
	public void sendEmailNoAttachFile(EmailModel emailModel) throws Exception {
		// TODO Auto-generated method stub

		/**
		 * 获得发送人
		 */
		String tmpUserName = emailModel.getFrom();
		/**
		 * 判断邮件用户名是否为空，为空取spring配置文件中的默认用户名
		 */
		if (tmpUserName == null || "".equalsIgnoreCase(tmpUserName)) {
			emailModel.setFrom(javaMail.getUsername());
		}
		/**
		 * 创建一个MimeMessage对象
		 */
		MimeMessage mimeMessage = javaMail.createMimeMessage();
		/**
		 * 创建一个MimeMessageHelper对象
		 */
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GBK");
		// MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
		// true);

		/**
		 * 邮件群发人分析
		 */
		String tmpToUser = emailModel.getTo();
		/**
		 * 群发接收人
		 */
		String[] arrToUser = tmpToUser.split(";");

		/**
		 * 设置发送人
		 */
		messageHelper.setFrom(emailModel.getFrom());

		/**
		 * 设置标题
		 */
		messageHelper.setSubject(emailModel.getTitle());
		/**
		 * 设置内容
		 */
		messageHelper.setText(emailModel.getContent(), true);
		// messageHelper.setText(emailModel.getContent());

		try {

			/**
			 * 设置发送人
			 */
			messageHelper.setTo(arrToUser);
			/**
			 * 发送邮件
			 */
			javaMail.send(mimeMessage);
		}
		catch (Exception ex) {
			throw ex;
		}
	}

	/**
	 * 执行发送邮件没有附件情况
	 * @param title
	 * @param content
	 * @param emailTo
	 */
	public void sendEmail(String title,String content,String emailTo)throws Exception{
		EmailModel sendInfo = new EmailModel();

		sendInfo.setTo(emailTo);
		sendInfo.setTitle(title);
		sendInfo.setContent(content);
		try {
			this.sendEmailNoAttachFile(sendInfo);
		}
		catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 发送更新接送信息的邮件
	 *
	 * @param emailPickDropModelList 变化的接送信息
	 */
	@Override
	public void pickAndDropSendMail(List<PickDropModel> emailPickDropModelList) {
		if(null != emailPickDropModelList && emailPickDropModelList.size() > 0){
			try {
				this.sendEmail("力行接送信息更新-"+DateUtil.getPreviousDateTimeString("yyyyMMdd"),getPickAndDropTable(emailPickDropModelList), QyerConfig.getInstance().getString(QyerContants.QYER_MAIL_PICK_AND_DROP,"ping.jiang@qyer.com"));
			} catch (Exception e) {
				logger.error("发送接送信息邮件异常:",e);
			}
		}
	}

	/**
	 * 发送更新日期价格信息的邮件
	 *
	 * @param priceResult 变化的日期价格信息
	 */
	@Override
	public void priceSendMail(Map<String,Map<String,List<Price>>> priceResult, Map<String,Map<String,String>> specficationMap, Map<String,String> saleNames) {
		if(null != priceResult && priceResult.size() > 0){
			try {
				this.sendEmail("力行日期价格更新-"+DateUtil.getPreviousDateTimeString("yyyyMMdd"),getPriceTable(priceResult,specficationMap,saleNames),QyerConfig.getInstance().getString(QyerContants.QYER_MAIL_PRICE,"ping.jiang@qyer.com"));
			} catch (Exception e) {
				logger.error("发送日期价格邮件异常:",e);
			}
		}
	}

	/**
	 * 发送邮件的html模板
	 * @param table 表格内容
	 * @param title	html模板页签标题
	 * @param mainTitle 表格主标题
	 * @param subjectSubject 表格副标题
     * @return
     */
	public String htmlTempletes(String table,String title,String mainTitle,String subjectSubject){
		if(QyerUtils.isNotEmpty(table)){
			StringBuffer content = new StringBuffer();
			content.append("<html>\n" )
					.append("<head>\n" )
					.append("  <meta charset=\"utf-8\"/>\n" )
					.append("  <title>\n" )
					.append(title)
					.append("\n" )
					.append("  </title>\n" )
					.append("</head>\n" )
					.append("<body style=\"padding:0; margin:0;\">\n" )
					.append("<table style=\" padding:0; margin:0 auto; font-family:'microsoft YAHEI'; color:#555;\" width=\"880\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" )
					.append("  <tr>\n" )
					.append("    <td>\n" )
					.append("      <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" )
					.append("            <tbody>\n" )
					.append("              <tr>\n" )
					.append("                <td style=\"background: #fff; padding: 20px 20px; font-size:24px; color:#333;\">\n" )
					.append(mainTitle)
					.append("                    \n" )
					.append("                </td>\n" )
					.append("              </tr>\n" )
					.append("          </table>\n" )
					.append("    </td>\n" )
					.append("  </tr>\n" )
					.append("  <tr>\n" )
					.append("    <td><strong style=\"background:#ddd; display:block; margin:0; padding:0 20px; line-height:44px; font-size:18px;\">")
					.append(subjectSubject)
					.append("</strong></td>\n" )
					.append("  </tr>\n" )
					.append("  <tr>\n" )
					.append("    <td style=\"padding-top:20px;\">\n" )
					.append("      <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"border:1px solid #ddd; border-collapse:collapse;\">\n" )
					.append(table)
					.append("      </table>\n" )
					.append("    </td>\n" )
					.append("  </tr>\n" )
					.append("</table>\n" )
					.append("</body>\n" )
					.append("</html>");
			return content.toString();
		}
		return null;
	}

	/**
	 * 拼接日期价格表格部分要显示的内容
	 * @param priceList	日期价格信息列表
	 * @param specficationMap	规则中英文对照信息
     * @return	返回拼接后的结果
     */
	public String getPriceTable(Map<String,Map<String,List<Price>>> priceList, Map<String,Map<String,String>> specficationMap, Map<String,String> saleNames){
		if(null != priceList){
			try {
				StringBuilder content = new StringBuilder();
				List<String> productCodes = new ArrayList<String>();
				Iterator entryIterator = priceList.entrySet().iterator();
				while (entryIterator.hasNext())
				{
					Map.Entry<String,Map<String,List<Price>>> entry = (Map.Entry<String,Map<String,List<Price>>>)entryIterator.next();
					String key = entry.getKey();
					Map<String,List<Price>> value = entry.getValue();
					productCodes.add(key);
				}
				//表格头部分
				content.append("            <tr>\n" )
						.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">产品code</th>\n" )
						.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">套餐＋规格名称</th>\n" )
						.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">供应价(净价)</th>\n" )
						.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">建议售价</th>\n" )
						.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">服务费</th>\n" )
						.append("            </tr>\n" );
				//表格body部分
				for(String productCode:productCodes){
					Map<String,List<Price>> saleCodes = priceList.get(productCode);
					Map<String,String> specficationMaps =specficationMap.get(productCode);
					Iterator saleCodesEntryIterator = saleCodes.entrySet().iterator();
					while (saleCodesEntryIterator.hasNext())
					{
						Map.Entry<String,List<Price>> saleCodesEntry = (Map.Entry<String,List<Price>>)saleCodesEntryIterator.next();
						String key = saleCodesEntry.getKey();
						List<Price> value = saleCodesEntry.getValue();
						logger.info("============================打印最终更新的价格列表结果：" + value);
						logger.info("============================打印规格列表结果：" + specficationMaps);
						for(Price price:value){
							if(price.getSpecificationId().equals("P3")){
								continue;
							}
							content.append("            <tr>\n" )
									.append("              <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
									.append(productCode).append("</th>\n" )
									.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
									.append(saleNames.get(key)).append(specficationMaps.get(price.getSpecificationId())).append("</th>\n" )
									.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
									.append(price.getNetPrice()).append("</th>\n" )
									.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
									.append(price.getRetailPrice()).append("</th>\n" )
									.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
									.append(price.getFee()).append("</th>\n" )
									.append("            </tr>\n" );
						}
					}

				}
				return htmlTempletes(content.toString(),"日期价格","力行日期价格更新-"+DateUtil.getPreviousDateTimeString("yyyyMMdd"),"日期价格相关更新信息");
			} catch (Exception e) {
				logger.error("发送日期价格邮件异常:",e);
			}
		}
		return null;
	}

	/**
	 * 拼接接送信息表格部分需要显示的内容
	 * @param emailPickDropModelList	接送信息列表
	 * @return	返回拼接后的结果
     */
	public String getPickAndDropTable(List<PickDropModel> emailPickDropModelList){
		if(null != emailPickDropModelList && emailPickDropModelList.size() > 0){
			try {
				StringBuilder content = new StringBuilder();
				content.append("            <tr>\n" )
						.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">产品code</th>\n" )
						.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">接送类型</th>\n" )
						.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">集合时间</th>\n" )
						.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">集合地点</th>\n" )
						.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">集合具体地址</th>\n" )
						.append("            </tr>\n" );
				for(PickDropModel emailPickDropModel:emailPickDropModelList){
					content.append("            <tr>\n" )
							.append("              <th style=\"background:#fff; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
							.append(emailPickDropModel.getProductCode()).append("</th>\n" )
							.append("              <th style=\"background:#fff; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
							.append(emailPickDropModel.getType()).append("</th>\n" )
							.append("              <th style=\"background:#fff; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
							.append(QyerUtils.isEmpty(emailPickDropModel.getTime())?"":emailPickDropModel.getTime()).append("</th>\n" )
							.append("              <th style=\"background:#fff; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
							.append(QyerUtils.isEmpty(emailPickDropModel.getLocation())?"":emailPickDropModel.getLocation()).append("</th>\n" )
							.append("              <th style=\"background:#fff; font-size:14px; line-height:32px; border:1px solid #ccc;\">")
							.append(QyerUtils.isEmpty(emailPickDropModel.getAddress())?"":emailPickDropModel.getAddress()).append("</th>\n" )
							.append("            </tr>\n" );
				}
				return htmlTempletes(content.toString(),"接送信息", "力行接送信息更新-"+DateUtil.getPreviousDateTimeString("yyyyMMdd"),"接送相关更新信息");
			} catch (Exception e) {
				logger.error("发送接送信息邮件异常:",e);
			}
		}
		return null;
	}
}
